package com.keyin.android.view;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

public class SegmentControl extends LinearLayout {

	private ChangeFocusListener listener;
	private View focused;

	public SegmentControl(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();
		
		setDefaultFocus(0);
	}
	
	public void setDefaultFocus(int focusIndex){
		focused = getChildAt(focusIndex);
		focused.setClickable(false);
	}

	public void setChangeFocusListener(ChangeFocusListener adapter) {
		this.listener = adapter;
	}
	
	public void notifyDataChanged(){
		setChangeFocusListener(listener);
	}
	
	protected void changeFocus(View focus, View lastFocused){
		if (lastFocused != null){
			if (focus == focused){
				return;
			}
			lastFocused.setClickable(true);
			listener.onBlur(lastFocused, getFocusIndex());
		}
		
		focused = focus;
		focused.setClickable(false);
		listener.onFocus(focused, getFocusIndex());
	}
	
	public int getFocusIndex(){
		int cnt = getChildCount();
		for (int i = 0; i < cnt; i ++){
			if (focused != null && focused == getChildAt(i)){
				return i;
			}
		}
		return 0;
	}
	
	public void changeFocus(int focusIndex){
		changeFocus(getChildAt(focusIndex), focused);
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		int x = (int) ev.getX();
		int y = (int) ev.getY();

		int count = getChildCount();

		for (int i = 0; i < count; i++) {
			View v = getChildAt(i);
			Rect r = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());

			if (r.contains(x, y)) {
				changeFocus(v, focused);
				break;
			}
		}
		return true;
	}
}
